import { equips, loadSuits, findEquipBySuit, loadEffectives, suitCountFilter, getEquipImage } from "@/core/equips"
import { Equip, equip_parts } from "@/core/equips"
import IButton from "@/components/button/button"
import { defineComponent, ref, watch } from "vue"
import { rarities } from "@/core/item"

export default defineComponent({
    name: "suits",
    components: { IButton },
    setup() {
        const suits = loadSuits()

        const checkedEquips = ref<Set<string>>(new Set())

        function checkEquip(equip: string) {
            if (checkedEquips.value.has(equip)) {
                checkedEquips.value.delete(equip)
            } else {
                checkedEquips.value.add(equip)
            }
        }

        const matrix_count = ref(0)

        watch(
            checkedEquips,
            val => {
                const list = equips.filter(e => val.has(e.name))
                let effectives = loadEffectives(list, suitCountFilter())
                matrix_count.value = effectives.length
            },
            {
                deep: true
            }
        )

        function checkSuit(suit_name: string) {
            const arr = equips.filter(e => e.suit_name == suit_name).map(e => e.name)
            arr.forEach(checkEquip)
        }

        function isChecked(equip: Equip) {
            return checkedEquips.value.has(equip.name)
        }

        function compare(a: Equip, b: Equip): number {
            const ra = rarities.indexOf(a.rarity || "epic")
            const rb = rarities.indexOf(b.rarity || "epic")
            const r = rb - ra
            if (r) {
                return r
            }
            const pa = equip_parts.indexOf(a.part)
            const pb = equip_parts.indexOf(b.part)
            return pa - pb
        }

        return () => (
            <div class="flex-wrap">
                {suits.map(suit => (
                    <div class="flex mt-2 items-center" key={suit}>
                        <calc-button onClick={() => checkSuit(suit)} class="mr-3 w-35 font-sm" v-trans:items={suit}></calc-button>
                        {findEquipBySuit(suit)
                            .sort(compare)
                            .map(equip => (
                                <div class="icon mr-2" onClick={() => checkEquip(equip.name)}>
                                    <div class={{ "icon-lay": !isChecked(equip) }}></div>
                                    <img src={getEquipImage(equip)} />
                                </div>
                            ))}
                    </div>
                ))}
            </div>
        )
    }
})
